<template>
  <div>
    <Card dis-hover>
      <h3>
        {{ taskName }}
      </h3>
      <ButtonGroup slot="extra">
        <Button @click="approvalInfo" type="warning" style="background: #EF5350;" :loading="buttonloading"
                v-if="approval">
          <Icon type="ios-bookmark"/>
          审批
        </Button>
        <Button @click="returnTo">
          返回
          <Icon type="ios-arrow-forward"/>
        </Button>
      </ButtonGroup>
    </Card>
    <Card dis-hover style="margin: 10px;">
      <Spin fix v-if="spinShow">
        <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
        <div>Loading</div>
      </Spin>
      <div :style="{height: bodyHeight + 'px', overflowY: 'auto', overflowX: 'hidden', }">
        <Form ref="formCustom" :model="formData" :rules="ruleCustom" label-position="top">
          <Row :gutter="16">
            <Col span="12">
              <FormItem label="伤亡人员姓名">
                <Input v-model="report.victim" type="text" readonly/>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="工种或岗位">
                <Input v-model="report.position" type="text" readonly/>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <Col span="12">
              <FormItem label="事故时间">
                <Input v-model="report.sartDateStr" type="text" readonly/>
              </FormItem>
            </Col>
            <Col span="12">
              <FormItem label="事故类别">
                <Input v-model="report.accTypeName" type="text" readonly/>
              </FormItem>
            </Col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="就业类型">
                <Input v-model="report.membershipName" type="text" readonly/>
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="伤害程度">
                <Input v-model="report.injuryLevelName" type="text" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="12">
              <FormItem label="创建人">
                <Input v-model="report.userName" type="text" readonly/>
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="创建时间">
                <Input v-model="report.createDate" type="text" readonly/>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16">
            <i-col span="24">
              <FormItem label="事故报告简述">
                <Input v-model="report.reportDesc" type="textarea" :readonly="read"/>
              </FormItem>
            </i-col>
          </Row>

          <Row :gutter="16" v-if="!read">
            <i-col span="24">
              <FormItem label="审计报告附件">
                <Upload ref="upload"
                        :before-upload="beforeUpload"
                        :show-upload-list="true"
                        :max-size="10240"
                        multiple
                        type="drag"
                        :action="fileUrl">
                  <div style="padding: 10px">
                    <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                    <p>点击将文件拖拽到这里上传</p>
                    <span style="font-size:8px;color: #797a64">支持扩展名：.rar .zip .doc .docx .pdf...</span>
                  </div>
                </Upload>
                <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                  <a @click="downloadFile(report.reportId, item)">{{ item.fileName }}</a>
                  <Button type="text" icon="md-trash" @click="remove1(item.id)"
                          style="margin-left: 5px;margin-bottom: 3px"/>
                </div>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16" v-else>
            <Col span="24">
              <FormItem label="事故报告书：">
                <div v-show="uploadList.length>0" v-for="item in uploadList" :key='item'>
                  <a @click="downloadFile(report.briefId,item)">{{ item.fileName }}</a>
                </div>
              </FormItem>
            </Col>
          </Row>
          <div v-if="approval">
            <Divider orientation="left" v-if="read">操作信息</Divider>
            <Row :gutter="16" v-if="read">
              <i-col span="8">
                <FormItem label="审批结果：" prop="route">
                  <Select filterable v-model="formData.route" @on-change="routePush">
                    <Option v-for="item in routeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
                  </Select>
                </FormItem>
              </i-col>
            </Row>
            <Row :gutter="16" v-if="read">
              <i-col span="24">
                <FormItem label="处理意见：" prop="opinion">
                  <Input type="textarea" v-model="formData.opinion"/>
                </FormItem>
              </i-col>
            </Row>
          </div>

        </Form>
      </div>
    </Card>

  </div>
</template>

<script>
import {Api} from '../../../../api'
import {sessionStorage} from '@/common/cacheUtils.js';

export default {
  name: "adtReportForm",
  data() {
    return {
      taskName: '',
      buttonloading: false,
      variables: {},
      approval: false,
      spinShow: true,
      read: true,
      taskInfo: {},
      bodyHeight: '',
      formData: {},
      ruleCustom: {
        route: [{
          validator: (rule, value, callback) => {
            if (this.formData.route == null || this.formData.route == '' || this.formData.route == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
        opinion: [{
          validator: (rule, value, callback) => {
            if (this.formData.opinion == null || this.formData.opinion == '' || this.formData.opinion == undefined) {
              callback(' ')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }],
      },
      routeList: [
        {
          id: '1',
          name: '合格'
        },
        {
          id: '2',
          name: '不合格'
        }
      ],
      ifRoute: false,
      ifFile: false,
      ifReportOpinion: true,
      noReportOpinion: true,
      report: {},
      userInfo: {},
      uploadList: [],
      fileUrl: Api.interestedPartiesUserFile,
    }
  },
  mounted() {
    this.bodyHeight = window.innerHeight - 175;
    this.taskName = this.$route.query.taskName;
    this.taskInfo = this.$route.query;
    this.userInfo = sessionStorage('userId').getObject('userId');
    this.formData = {
      userName: this.userInfo.userName,
      taskId: this.taskInfo.taskId,
      createUserId: this.userInfo.userId,
      createDateStr: this.formatDate(new Date(), 'yyyy-MM-dd'),
      procinstId: this.taskInfo.procinstId,

    };
    if (this.taskInfo.status == 'done' || this.taskInfo.status == 'self') {
      this.approval = false;
      this.read = true;
    } else {
      if (this.taskInfo.procinstState === '2') {
        this.read = false;
      } else {
        this.read = true;
      }
      this.approval = true;
      this.queryFormList();

    }


    this.query();
  },
  methods: {
    queryFormList() {
      this.$http.get(Api.getProcinstForm + '/' + this.taskInfo.taskId).then(function (response) {
        if (response.data.variables != undefined) {
          this.variables = response.data.variables;
        }
      });
    },
    sendMessage(procinstId){
      let data = { content: "您有一条事故报告需要审批，请登录安全环保信息平台进行审批" };
      this.$http.post(Api.sendMessage +"/"+procinstId , data);
    },
    routePush(value) {
      if (value === '1') {
        this.$set(this.formData, 'opinion', '同意');
      } else {
        this.$set(this.formData, 'opinion', null);
      }
    },
    messages(){
      let _this = this;
      if(_this.taskName == '上报人'){
        _this.sendMessage(_this.variables.user1);
      }else if(_this.taskName == '企业负责人审批'){
        _this.sendMessage( _this.formData.route == 1? _this.variables.user2: _this.variables.createUser);
      }else if(_this.taskName == '二级集团安全环保管理人员审批'){
        if (_this.variables.user3){
          //三级审批
          _this.sendMessage( _this.formData.route == 1? _this.variables.user3: _this.variables.createUser);
        }else{
          //二级审批
          if (_this.formData.route != 1){
            _this.sendMessage(_this.variables.createUser);
          }
        }
      }else if(_this.taskName == '集团安全环保管理人员审批'){
        if (_this.formData.route != 1){
          _this.sendMessage(_this.variables.createUser);
        }
      }
    },
    approvalInfo() {
      let _this = this;
      this.$refs['formCustom'].validate((valid) => {
        if (valid) {
          _this.buttonloading = true;
          if (this.read) {
            _this.$http.get(Api.taskComplete, {
              params: this.formData
            }).then(function (response) {
              if (response.data.status == 200) {
                // _this.messages();
                _this.sendMessage(_this.taskInfo.procinstId);
                _this.$Message.success({content: '保存成功', duration: 4});
                _this.returnTo();
              } else {
                _this.$Message.error({content: '保存失败', duration: 4});
              }
              _this.buttonloading = false;
            });
          } else {
            let url = Api.report;
            _this.report.updateUserId = sessionStorage('userId').getObject('userId').userId
            _this.report.updateOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
            _this.$http.put(url, _this.report).then((res) => {
              if (res.data.status == 200) {
                this.$http.get(Api.taskComplete, {
                  params: _this.formData
                }).then(function (response) {
                  if (response.data.status == 200) {
                    // _this.messages();
                    _this.sendMessage(_this.taskInfo.procinstId);
                    this.$Message.success({content: '保存成功', duration: 4});
                    this.returnTo();
                  } else {
                    this.$Message.error({content: '保存失败', duration: 4});
                  }
                  this.buttonloading = false;
                });
              }
            }).catch(e => {
              this.$Message.error('请求失败');
              this.buttonloading = false;
            })
          }

        } else {
          this.$Message.error({content: '请填写完整！', duration: 4});
        }
      });
    },
    returnTo() {
      debugger;
      this.$router.go(-1);
    },
    query() {
      this.$http.get(Api.report + '/' + this.taskInfo.workId).then(function (response) {
        if (response.data.status == 200) {
          this.report = response.data.data;
        }
        this.getFiles();

        this.spinShow = false;
      });
    },

    async getFiles() {
      let url = this.fileUrl + '/' + this.report.reportId + '/files/reportFile'
      await this.$http.get(url).then((res) => {
        if (res.data.result == "success") {
          this.uploadList = res.data.data;
        }
      })
    },
    downloadFile(guideId, file) {
      let url = this.fileUrl + '/file/' + file.id;
      this.$http.get(url, {
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob);
        aLink.download = file.fileName; //标题
        aLink.click();
        document.body.appendChild(aLink);
      })
    },
    remove1(id) {
      let url = this.fileUrl + '/file/' + id;
      this.$http.delete(url).then((res) => {
        this.getFiles();
      })
    },
    beforeUpload(file) {
      let formData = new FormData();
      formData.append("files", file); // 文件对象
      let url = this.fileUrl + '/' + this.report.reportId + '/files/reportFile';
      this.$http.post(url, formData).then((res) => {
        if (res.data.result == "success") {
          this.$Message.info("文件上传成功");
          this.getFiles();
        }
      })
      return false;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },
  }

}
</script>

<style scoped>
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
</style>
